package com.tianxiao.faas.application.web.corner;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.tianxiao.faas.api.param.corner.LoginParam;
import com.tianxiao.faas.api.param.corner.LoginResult;
import com.tianxiao.faas.api.param.corner.WxLoginParam;
import com.tianxiao.faas.application.aop.AuthenticationAopConfig;
import com.tianxiao.faas.biz.corner.service.user.UserLoginService;
import com.tianxiao.faas.biz.service.corner.WeChatService;
import com.tianxiao.faas.common.access.Access;
import com.tianxiao.faas.common.result.Result;
import com.tianxiao.faas.mapper.model.LoginInfoModel;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("app/user")
public class LoginController {
    @Resource
    private UserLoginService userLoginService;
    @Resource
    private WeChatService weChatService;
    @Value("${spring.server.domain}")
    private String domain;

    @RequestMapping(value = "/wx_login")
    public Result<LoginResult> wxLogin(@RequestBody WxLoginParam param, HttpServletResponse response) {
        // 用户非敏感信息：rawData
        // 签名：signature
        String rawData = param.getRawData();
        String code = param.getCode();
        String signature = param.getSignature();
        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject sessionKeyOpenId = weChatService.getSessionKeyOrOpenId(code);
        // 3.接收微信接口服务 获取返回的参数
        String sessionKey = sessionKeyOpenId.getString("session_key");

        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
//        String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
//        if (signature != null && !signature.equals(signature2)) {
//            return Result.builder().data(true).success(false).msg("签名验证失败");
//        }
        rawData = rawData == null ? "{}" : rawData;
        LoginResult token = userLoginService.wxLogin(rawData, sessionKeyOpenId);
        Cookie cookie = new Cookie(Access.TOKEN, token.getToken());
        cookie.setDomain(domain);
        cookie.setPath("/");
        response.addCookie(cookie);
        return Result.builder().data(token).isLogin(true).success(true);
    }

//    @RequestMapping(value = "/login")
//    public Result<Boolean> login(@RequestParam("mobile") String mobile, HttpServletResponse response) {
//        LoginInfoModel login = userLoginService.login(mobile, "corner@123!");
//        Cookie cookie = new Cookie(Access.TOKEN, login.getToken());
//        cookie.setDomain(domain);
//        cookie.setPath("/");
//        response.addCookie(cookie);
//        return Result.builder().data(true).isLogin(true).success(true);
//    }

    @RequestMapping(value = "/admin/login")
    public Result<Boolean> adminLogin(@RequestBody LoginParam loginParam, HttpServletResponse response) {
        LoginInfoModel login = userLoginService.login(loginParam.getMobile(), loginParam.getPassword());
        Cookie cookie = new Cookie(Access.TOKEN, login.getToken());
        cookie.setDomain(domain);
        cookie.setPath("/");
        response.addCookie(cookie);
        Cookie cookie1 = new Cookie("SameSite", "None");
        response.addCookie(cookie1);
        response.addHeader(Access.TOKEN, login.getToken());
        return Result.builder().data(true).isLogin(true).success(true);
    }

    @RequestMapping(value = "/admin/assign")
    @Access(access = {"admin"}, action = "分配管理员")
    public Result<Boolean> assign(@RequestBody LoginParam loginParam) {
        userLoginService.register(loginParam.getMobile(), loginParam.getName(), loginParam.getPassword(), "", Lists.newArrayList("admin"));
        return Result.builder().data(true).isLogin(true).success(true);
    }

    @RequestMapping("/logout")
    @Access
    public Result<Boolean> login(HttpServletRequest request, HttpServletResponse response) {
        String token = AuthenticationAopConfig.getToken(request);
        Cookie cookie = new Cookie(Access.TOKEN, "");
        cookie.setMaxAge(10);
        response.addCookie(cookie);
        userLoginService.logout(token);
        return Result.builder().data(true).isLogin(false).success(true);
    }
}
